﻿import type { Router, RouteLocationNormalized, NavigationGuardNext } from 'vue-router';
import { ref, nextTick } from 'vue';
import { useUserStore } from '@/stores/user';
// @ts-ignore
import NProgress from 'nprogress';
import { RoutesAlias } from '../routesAlias';
import { asyncRoutes } from '../routes/asyncRoutes';
import { staticRoutes } from '../routes/staticRoutes';

// 是否已注册动态路由
const isRouteRegistered = ref(false);

// 跟踪是否需要关闭 loading
const pendingLoading = ref(false)



/**
 * 前置守卫路由逻辑
 * @param router 
 * 1.查看是否登录 （检查是否为静态路由）
 * 2.处理动态路由注册
 * 
 * 
 * 
 */

/**
 * 设置路由全局前置守卫
 */
export function setupBeforeEachGuard(router: Router): void {
    router.beforeEach(async (to: RouteLocationNormalized, from: RouteLocationNormalized, next: NavigationGuardNext) => {
        try {
            await handleRouteGuard(to, from, next, router);
        } catch (error) {
            console.error('路由守卫处理失败:', error);
            next({ name: 'Exception500' });
        }
    });

    // 设置后置守卫以关闭 loading 和进度条
    // setupAfterEachGuard(router);
}

/**
 * 处理路由守卫逻辑
 */
async function handleRouteGuard(
    to: RouteLocationNormalized,
    from: RouteLocationNormalized,
    next: NavigationGuardNext,
    router: Router
): Promise<void> {
    const userStore = useUserStore();

    NProgress.start();

    // 处理登录状态
    if (!(await handleLoginStatus(to, userStore, next))) {
        return;
    }

    // 处理动态路由注册
    if (!isRouteRegistered.value && userStore.isLogin) {
        await handleDynamicRoutes(to, from, next, router);
        return;
    }

    // 处理根路径跳转到首页
    if (userStore.isLogin && isRouteRegistered.value && handleRootPathRedirect(to, next)) {
        return;
    }

    // 处理已知的匹配路由
    if (to.matched.length > 0) {
        setWorktab(to);
        setPageTitle(to);
        next();
        return;
    }

    // 未匹配到路由，跳转到 404
    next({ name: 'Exception404' });
}

/**
 * 处理登录状态
 */
async function handleLoginStatus(
    to: RouteLocationNormalized,
    userStore: ReturnType<typeof useUserStore>,
    next: NavigationGuardNext
): Promise<boolean> {
    // 检查是否为静态路由
    const isStaticRoute = isRouteInStaticRoutes(to.path);

    if (!userStore.isLogin && to.path !== RoutesAlias.Login && !isStaticRoute) {
        userStore.logOut();
        next({ name: 'Login' });
        return false;
    }
    return true;
}

/**
 * 检查路由是否为静态路由
 */
function isRouteInStaticRoutes(path: string): boolean {
    const checkRoute = (routes: any[], targetPath: string): boolean => {
        return routes.some(route => {
            if (route.path === targetPath) {
                return true;
            }
            if (route.children && route.children.length > 0) {
                return checkRoute(route.children, targetPath);
            }
            return false;
        });
    };

    return checkRoute(staticRoutes, path);
}


/**
 * 处理动态路由注册
 */
async function handleDynamicRoutes(
  to: RouteLocationNormalized,
  from: RouteLocationNormalized,
  next: NavigationGuardNext,
  router: Router
): Promise<void> {
  // 显示 loading 并标记 pending
  pendingLoading.value = true
//   loadingService.showLoading()

  try {
    // 获取用户信息
    await fetchUserInfoIfNeeded(from)

    // 获取菜单数据并注册路由
    await getMenuData(router)

    // 处理根路径跳转
    if (handleRootPathRedirect(to, next)) {
      return
    }

    next({
      path: to.path,
      query: to.query,
      hash: to.hash,
      replace: true
    })
  } catch (error) {
    console.error('动态路由注册失败:', error)
    // 401 错误：axios 拦截器已处理退出登录，取消当前导航即可
    if (isUnauthorizedError(error)) {
      next(false)
      return
    }
    // 其他错误：跳转到 500 页面
    next({ name: 'Exception500' })
  }
}
